import { _decorator, Component, instantiate, Node, Prefab, Vec2 } from 'cc';
import { CommonLevel } from './CommonLevel';
import { Tools } from '../../../ISUtility/Script/Tools';
import { UnitMgr } from '../UnitMgr';
const { ccclass, property } = _decorator;

@ccclass('EdibleLayer')
export class EdibleLayer extends Component {

    @property
    public ScaleMin: number = 0.5; 

    @property
    public ScaleMax: number = 1.0; 
    
    @property({ type: Vec2 })
    public Grid: Vec2 = new Vec2();

    @property({ type: Number, range: [0, 1] })
    public Density: number = 0.25;

    @property({ type: [Prefab] })
    public EdiblePrefabs: Prefab[] = [];


    public Refresh() {
        let floor = this.node.getComponent(CommonLevel)?.Floor;
        for (let i = 0; i < this.Grid.x; ++i) {
            for (let j = 0; j < this.Grid.y; ++j) {

                if (0 == i || 0 == j) continue;
                if (this.Grid.x == i || this.Grid.y == j) continue;

                let random = Math.random();
                if (random > this.Density)
                    continue;

                let x = i * (floor.size.x / this.Grid.x) - floor.size.x * 0.5;
                let z = j * (floor.size.z / this.Grid.y) - floor.size.z * 0.5;

                if (x == 0 && z == 0) continue;

                x += (Math.random() - 0.5) * 2 * 2;
                z += (Math.random() - 0.5) * 2 * 2;

                if (x == 0 && z == 0) continue;


                let index = Tools.RangeInt(0, this.EdiblePrefabs.length - 1);
                let prefab = this.EdiblePrefabs[index];
                let edible = instantiate(prefab);
                UnitMgr.inst.node.addChild(edible);
                edible.setPosition(x, 0, z);
                let s = Tools.Range(this.ScaleMin,this.ScaleMax);
                edible.setScale(s,s,s);
            }
        }
    }


}


